<?php
namespace app\api\controller;
use think\Controller;
use think\Config;

class User extends Controller{
    //获取Openid
    public function getOpenid(){
   
        if(isset($_GET['code'])){
            $code = $_GET['code'];
            $url='https://api.weixin.qq.com/sns/jscode2session?appid='.Config::get('wechat.appid').'&secret='.Config::get('wechat.appsecret').'&js_code='.$code.'&grant_type=authorization_code';
            $result = MyCurlOfGet($url);
            $data = array(
                "code" => 200,
                "msg" =>'请求成功',
                "openid" => $result['openid'],
                'session_key' => $result['session_key']
            );
        } else {
            $data = array(
                "status" => 201,
                "msg" => "code参数获取失败"
            );
        }
        
        return json_encode($data);
    }

    //进入登录  生成新用户
    public function login(){
        $appid = Config::get('wechat.appid');
        $sessionKey = input('post.sessionKey');
        $encryptedData = input('post.encryptedData');
        $iv = input('post.iv');
        //检测传参
        if($sessionKey == 'undefined' || $sessionKey =='null' || $sessionKey == ''){
            $info['code'] = 401;
            $info['msg'] = '缺少sessionKey';

            return json_encode($info);
        }elseif($encryptedData == 'undefined' || $encryptedData =='null' || $encryptedData == ''){
            $info['code'] = 401;
            $info['msg'] = '缺少encryptedData';

            return json_encode($info);
        }elseif($iv == 'undefined' || $iv =='null' || $iv == ''){
            $info['code'] = 401;
            $info['msg'] = '缺少iv';
            
            return json_encode($info);
        }

        //利用encryptData解密
        vendor('encryptData.wxBizDataCrypt');
        $pc = new \WXBizDataCrypt($appid,$sessionKey);
        $errCode = $pc->decryptData($encryptedData,$iv,$data);

        if($errCode == 0){
            $obj = json_decode($data,true);
            $openid = $obj['openId'];
            $nickName = $obj['nickName'];
            file_put_contents(ROOT_PATH.'Logs/userinfo.log', date('Y-m-d H:i')."=". $nickName . "\r\n\r\n", FILE_APPEND); 
            $addData = array(
                'name' => $nickName,
                'img' => $obj['avatarUrl'],
                'openid' =>$openid,
                );
            if(isset($obj['unionId'])){
               $addData['unionid'] = $obj['unionId'];
            }else{
               $addData['unionid'] = '';
            }
            $user_id = db('user') -> where("openid = '{$openid}'") -> value('user_id');
            if($user_id){
                db('user') -> where("user_id",$user_id) -> update($addData);
                $info['code'] = 200;
                $info['msg'] = '用户已注册';
                $info['user_id'] = $user_id;
                
                return json_encode($info); 
            }else{
                $leader = input('post.leader');
                if($leader){
                    if(!is_numeric($leader)){return json_encode(['code'=>401,'msg'=>'leader类型错误']);}
                    $addData['leader'] = $leader;
                    $upper_level_id = db('user')->where("user_id = {$leader}")->value('leader');
                    if($upper_level_id){$addData['upper_level_id'] = $upper_level_id;}
                }
                $addData['time'] = time();
                $user_id = db('user') -> insertGetId($addData);
                if($user_id){
                    $info['code'] = 200;
                    $info['msg'] = '新用户注册成功';
                    $info['user_id'] = $user_id;
                    
                    return json_encode($info);
                }else{
                    $info['code'] = 201;
                    $info['msg'] = '生成新用户失败';
                    
                    return json_encode($info);
                }
            }
        }else{
            $info['code'] = 401;
            $info['msg'] = '获取明文失败';
            $info['errCode'] = $errCode;
            return json_encode($info); 
        }
    }

    
}